package com.borya.dao.impl;

import com.borya.dao.MerchantPerfectionServiceDAO;
import com.borya.framework.annotation.Component;
import com.borya.framework.core.ServerSqlSession;
import com.borya.model.db.LoginLivingRecordInfo;
import com.borya.model.db.MerchantPerfectionRecordInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.time.Clock;
import java.util.ArrayList;
import java.util.List;

@Component("merchantPerfectionServiceDAO")
public class MerchantPerfectionServiceDAOImpl extends BaseDAOImpl implements MerchantPerfectionServiceDAO {

    private Logger log = Logger.getLogger(getClass());

    @Override
    public boolean insert(MerchantPerfectionRecordInfo recordInfo) {
        List<String> sqlList = new ArrayList<>();
        StringBuilder sb = new StringBuilder(256);
        sb.append("insert into tb_merchant_perfection_record set ");
        sb.append(" order_id='" + recordInfo.getOrderId() + "'");
        sb.append(",userid='" + recordInfo.getUserId() + "'");
        sb.append(",merchant_id='" + recordInfo.getMerchantId() + "'");
        sb.append(",dealer_id='" + recordInfo.getDealerId() + "'");
        sb.append(",source='" + recordInfo.getSource() + "'");
        sb.append(",identity_card='" + recordInfo.getIdentityCard() + "'");
        sb.append(",identity_card_name='" + recordInfo.getIdentityCardName() + "'");
        sb.append(",identity_card_address='" + recordInfo.getIdentityCardAddress() + "'");
        sb.append(",shop_address='" + recordInfo.getShopAddress() + "'");
        sb.append(",shop_specific_address='" + recordInfo.getShopSpecificAddress() + "'");
        sb.append(",type=" + recordInfo.getType());
        sb.append(",audit_type=" + recordInfo.getAuditType());
        sb.append(",result=" + recordInfo.getResult());
        sb.append(",status=" + recordInfo.getStatus());
        sb.append(",create_time=" + recordInfo.getCreateTime());
        sb.append(",merchant_type=" + recordInfo.getMerchantType());
        sb.append(",identify_photo_head='" + recordInfo.getIdentifyPhotoHead() + "'");
        sb.append(",identify_photo_front='" + recordInfo.getIdentifyPhotoFront() + "'");
        sb.append(",identify_photo_reverse='" + recordInfo.getIdentifyPhotoReverse() + "'");
        sb.append(",identify_photo_hand='" + recordInfo.getIdentifyPhotoHand() + "'");
        sb.append(",period='" + recordInfo.getPeriod() + "'");
        sb.append(",audit_time=" + recordInfo.getAuditTime());
        sqlList.add(sb.toString());

        if (1 == recordInfo.getResult() && StringUtils.isNotBlank(recordInfo.getShopAddress()) && StringUtils.isNotBlank(recordInfo.getShopSpecificAddress())) {
            sb.delete(0, sb.length());
            sb.append("update tb_merchant set ");
            sb.append("user_region='").append(recordInfo.getShopAddress()).append("'");
            sb.append(",store_address='" + recordInfo.getShopAddress() + recordInfo.getShopSpecificAddress() + "'");
            sb.append(" where merchant_id='").append(recordInfo.getMerchantId()).append("'");
            sqlList.add(sb.toString());
        }

        int[] res = executeBatch(sqlList);
        return res != null && res.length > 0;
    }

    @Override
    public MerchantPerfectionRecordInfo getByOrderId(String orderId) {
        try (ServerSqlSession session = getSqlDataSource().session()) {
            StringBuilder sql = new StringBuilder(256);
            sql.append("select * from tb_merchant_perfection_record ");
            sql.append(" where order_id='").append(orderId).append("'");
            sql.append(" limit 1");
            return session.executeQuery(sql.toString(), (rs) -> {
                if (rs != null && rs.next()) {
                    MerchantPerfectionRecordInfo merchant = new MerchantPerfectionRecordInfo();
                    merchant.setId(rs.getLong("id"));
                    merchant.setOrderId(rs.getString("order_id"));
                    merchant.setOrderId(rs.getString("merchant_id"));
                    merchant.setDealerId(rs.getString("dealer_id"));
                    merchant.setSource(rs.getString("source"));
                    merchant.setIdentityCard(rs.getString("identity_card"));
                    merchant.setIdentityCardName(rs.getString("identity_card_name"));
                    merchant.setIdentityCardAddress(rs.getString("identity_card_address"));
                    merchant.setShopAddress(rs.getString("shop_address"));
                    merchant.setShopSpecificAddress(rs.getString("shop_specific_address"));
                    merchant.setType(rs.getInt("type"));
                    merchant.setAuditType(rs.getInt("audit_type"));
                    merchant.setResult(rs.getInt("result"));
                    merchant.setStatus(rs.getInt("status"));
                    merchant.setCreateTime(rs.getLong("create_time"));
                    merchant.setUpdateTime(rs.getLong("update_time"));
                    merchant.setMerchantType(rs.getInt("merchant_type"));
                    merchant.setIdentifyPhotoHead(rs.getString("identify_photo_head"));
                    merchant.setIdentifyPhotoFront(rs.getString("identify_photo_front"));
                    merchant.setIdentifyPhotoReverse(rs.getString("identify_photo_reverse"));
                    merchant.setIdentifyPhotoHand(rs.getString("identify_photo_hand"));
                    merchant.setPeriod(rs.getString("period"));
                    merchant.setGztRheck(rs.getString("gzt_check"));
                    merchant.setAuditTime(rs.getLong("audit_time"));
                    merchant.setAutoAuditDesc(rs.getString("auto_audit_desc"));
                    merchant.setAuditCustomer(rs.getString("audit_customer"));
                    merchant.setMerchantId(rs.getString("merchant_id"));
                    merchant.setUserId(rs.getString("userid"));
                    return merchant;
                }
                log.warn("DB not found user,userId=" + orderId);
                return null;
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public boolean updateMerchantPerfection(MerchantPerfectionRecordInfo recordInfo) {
        final long nowTime = Clock.systemDefaultZone().millis();
        List<String> sqlList = new ArrayList<>();
        StringBuilder sb = new StringBuilder(256);
        sb.append("update tb_merchant_perfection_record set ");
        sb.append("result=").append(recordInfo.getResult());
        sb.append(",status=").append(recordInfo.getStatus());
        sb.append(",update_time=").append(recordInfo.getUpdateTime());
        sb.append(",gzt_check='").append(recordInfo.getGztRheck()).append("'");
        sb.append(",audit_time=").append(recordInfo.getAuditTime());
        sb.append(",auto_audit_desc='").append(recordInfo.getAutoAuditDesc()).append("'");
        sb.append(",audit_customer='").append(recordInfo.getAuditCustomer()).append("'");
        sb.append(" where id=").append(recordInfo.getId());
        sqlList.add(sb.toString());

        sb.delete(0, sb.length());
        sb.append("update tb_merchant_perfection_log set ");
        sb.append("merchant_perfection_id=").append(recordInfo.getId());
        sb.append(" where order_id='").append(recordInfo.getOrderId()).append("'");
        sqlList.add(sb.toString());

        if (1 == recordInfo.getResult()) {
            if (StringUtils.isNotBlank(recordInfo.getShopAddress()) && StringUtils.isNotBlank(recordInfo.getShopSpecificAddress())) {
                sb.delete(0, sb.length());
                sb.append("update tb_merchant set user_region='").append(recordInfo.getShopAddress()).append("'");
                sb.append(",store_address='").append(recordInfo.getShopAddress() + recordInfo.getShopSpecificAddress()).append("'");
                sb.append(" where merchant_id='").append(recordInfo.getMerchantId()).append("'");
                sqlList.add(sb.toString());
            }

            sb.delete(0, sb.length());
            sb.append("update tb_user_client_detail set ");
            sb.append(" modifytime=").append(nowTime);
            if (StringUtils.isNotBlank(recordInfo.getIdentifyPhotoHand())) {
                sb.append(",identify_photo_hand='").append(recordInfo.getIdentifyPhotoHand()).append("'");
            }
            if (StringUtils.isNotBlank(recordInfo.getIdentifyPhotoHead())) {
                sb.append(",identify_photo_head='").append(recordInfo.getIdentifyPhotoHead()).append("'");
            }
            if (StringUtils.isNotBlank(recordInfo.getIdentifyPhotoFront())) {
                sb.append(",identify_photo_front='").append(recordInfo.getIdentifyPhotoFront()).append("'");
            }
            if (StringUtils.isNotBlank(recordInfo.getIdentifyPhotoReverse())) {
                sb.append(",identify_photo_reverse='").append(recordInfo.getIdentifyPhotoReverse()).append("'");
            }
            if (StringUtils.isNotBlank(recordInfo.getIdentityCard())) {
                sb.append(",identity_card='").append(recordInfo.getIdentityCard()).append("'");
                sb.append(",paperscode='").append(recordInfo.getIdentityCard()).append("'");
            }
            if (StringUtils.isNotBlank(recordInfo.getIdentityCardName())) {
                sb.append(",identity_card_name='").append(recordInfo.getIdentityCardName()).append("'");
                sb.append(",user_name='").append(recordInfo.getIdentityCardName()).append("'");
            }
            if (StringUtils.isNotBlank(recordInfo.getIdentityCardAddress())) {
                sb.append(",identity_card_address='").append(recordInfo.getIdentityCardAddress()).append("'");
            }
            if (StringUtils.isNotBlank(recordInfo.getPeriod())) {
                sb.append(",period='").append(recordInfo.getPeriod()).append("'");
            }
            sb.append(" where userid='").append(recordInfo.getUserId()).append("'");
            sqlList.add(sb.toString());
        }

        int[] res = executeBatch(sqlList);
        return res != null && res.length > 0;
    }

    public boolean addLivingPreRecord(LoginLivingRecordInfo info, String merchantId, String minLimitSimilarity) {
        final long nowTime = Clock.systemDefaultZone().millis();
        StringBuilder sb = new StringBuilder(256);
        sb.append("insert into tb_login_living_record set ");
        sb.append("merchant_id='" + merchantId + "'");
        sb.append(",similarity='" + info.getSimilarity() + "'");
        sb.append(",limitSimilarity='" + minLimitSimilarity + "'");
        sb.append(",identifyPhoto='" + info.getIdentifyPhoto() + "'");
        sb.append(",create_time=" + nowTime);
        sb.append(",result=" + info.getResult());
        sb.append(",error_msg='" + info.getRemark() + "'");
        sb.append(",tencent_order_id='" + info.getTencentOrderId() + "'");
        sb.append(",userId='" + info.getUserId() + "'");
        sb.append(",terminal_type='" + info.getTerminalType() + "'");
        sb.append(",device_name='" + info.getDeviceName() + "'");
        sb.append(",app_type='" + info.getAppType() + "'");
        sb.append(",phoneNo='" + info.getPhoneNo() + "'");
        sb.append(",face_id='" + info.getFaceId() + "'");
        log.info("insert into tb_login_living_record sql:" + sb.toString());
        return executeUpdate(sb.toString());
    }
}
